package com.gg.communication.communication.tcp;

import com.gg.communication.communication.BaseCommunication;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author sakura
 * @since 2025-06-16
 */

public class TcpServer extends BaseCommunication {

    private final static Map<String, TcpSocketCommunication> socketCommunications = new ConcurrentHashMap<>();
    private ServerSocket serverSocket;

    public static BaseCommunication initServer() {
        if (getInstance() == null)
            getInstance(new TcpServer());
        return getInstance();
    }
    //private final Set<Socket> clientSockets = Collections.newSetFromMap(new ConcurrentHashMap<>());

    private static String getSocketKey(String host, int port) {
        return "/" + host;
    }

    public static BaseCommunication initInstance(String host, int port) throws IOException {
        if (socketCommunications.get(getSocketKey(host, port)) == null) {
            throw new IOException("设备不在线");
        }
        return socketCommunications.get(getSocketKey(host, port));
    }

    @Override
    protected void startCommunication() throws IOException {
        serverSocket = new ServerSocket(getPort());
        System.out.println("TCP server started on port " + getPort());
    }

    @Override
    public void doCommunicationSend(byte[] msg, String host, int port) throws IOException {
        Set<String> k = socketCommunications.keySet();
        for (String s : k) {
            if (s.contains(host + ":" + port)) {
                socketCommunications.get(s).doCommunicationSend(msg);
            }
        }

    }

    //@Override
    //protected void processQueue() {
    //
    //}
    //
    //@Override
    //protected void received() {
    //
    //}

    @Override
    public byte[] doReceive() throws Exception {
        try {
            if (!isRun) {
                return null;
            }
            Socket clientSocket = serverSocket.accept();
            //clientSockets.add(clientSocket);
            TcpSocketCommunication socketCommunication = new TcpSocketCommunication(clientSocket, this);
            String clientAddr = clientSocket.getInetAddress().toString();
            System.out.println("Client connected: " + clientAddr);
            socketCommunications.put(clientAddr, socketCommunication);


            // 为每个客户端启动独立的数据接收线程
            //new Thread(() -> handleClient(clientSocket)).start();
        } catch (Exception e) {
            close();
            if (super.isRun) {
                e.printStackTrace();
                System.err.println("Error accepting client connection: " + e.getMessage());
            }
        }
        return new byte[0];
    }


    public void closeClientSocket(Socket socket) {
        try {
            if (socket != null && !socket.isClosed()) {
                socket.close();
                //clientSockets.remove(socket);
                socketCommunications.remove(socket.getInetAddress().toString());
                System.out.println("Client disconnected: " + socket.getRemoteSocketAddress());
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Error closing client socket: " + e.getMessage());
        }
    }

    @Override
    public void close() throws IOException {
        Set<String> k = socketCommunications.keySet();
        for (String s : k) {
            socketCommunications.get(s).close();
        }
        if (serverSocket != null && !serverSocket.isClosed()) {
            serverSocket.close();
        }
        super.close();
    }
}
